/*
 * Copyright (C) 2012 TopCoder Inc., All Rights Reserved.
 */
package cn.itcast.javamail2.web.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Test;

import cn.itcast.javamail.Demo1;

/**
 * @author TCSASSEMBLER
 * @version 1.0 ()
 * @since 1.0
 */
public class SendMailServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	@Test
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			//Demo1.main(new String[]{});
			
			
			Context initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			Session session = (Session) envCtx.lookup("mail/ession");
			System.out.println(envCtx.lookup("mail/ession").getClass().getClassLoader().getClass().getName());
			System.out.println(Session.class.getClassLoader().getClass().getName());
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("niudongze123@163.com"));
			InternetAddress to[] = new InternetAddress[1];
			to[0] = new InternetAddress("1064765543@qq.com");
			message.setRecipients(Message.RecipientType.TO, to);
			message.setSubject("haha");
			message.setText("test");
			//Transport.send(message);
			Transport transport = session.getTransport();
			transport.connect("smtp.163.com", "niudongze123", "124578");
			transport.sendMessage(message, to);
			transport.close();
			
			response.getWriter().print("success");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
